package com.fingard.dsp.bank.directbank.bea11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;

import msoa.org.apache.commons.lang.StringUtils;


/**
 * BEA11-东亚银行银保通
 *
 * 需求描述:
 * 		1、通讯方式:FTP或者SFTP
 * 		2、交互字符集：GBK
 *
 * 渠道说明:
 * 		本接口适用于采用准实时批量代收付业务的场景，
 * 		具体上送时间点不再限制，一天只能传一个文件，若一天传了多个文件，则后面的文件直接拒绝，作为失败处理
 *
 * @author Cruise
 * @date 2020年03月10日
 */
public class BEA11BatPayRec extends BEA11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    /**
     * 批量代收付提交
     *
     * @param p_reqBat 批量代收付请求对象
     * @return 批量代收付响应对象
     * @throws Exception
     */
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        try {
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();

            // 文件明细
            while (p_reqBat.readRecord()) {
                String postScript = p_reqBat.reqBatchNO + "_" + p_reqBat.readedDetail.askNumber;

                String oppAct = "";
                String oppName = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    oppName = p_reqBat.readedDetail.recName;
                } else {
                    oppAct = p_reqBat.readedDetail.payAct;
                    oppName = p_reqBat.readedDetail.payName;
                }

                String payAmt = StringHelper.amountMultiply100(p_reqBat.readedDetail.payAmount);
                String certType = convertCertTypeToBank(p_reqBat.readedDetail.certType);
                String certNum = p_reqBat.readedDetail.certNum;
                String sourceNoteCode = p_reqBat.readedDetail.sourceNoteCode;
                if (StringHelper.isNullOrEmpty(sourceNoteCode)) {
                    sourceNoteCode = p_reqBat.readedDetail.memo.trim();
                }
                
                String inPolicyNo = p_reqBat.readedDetail.srcXElement.getSingleText(getBankConfig().getValueAsString("inPolicyNo"));
                if (StringUtils.isNotEmpty(inPolicyNo)) {
                	sourceNoteCode = inPolicyNo;
                }
                
                // 明细信息:保险公司代码|业务代码|客户银行帐号|金额|客户名称|客户证件类型|证件号码|业务类型|缴费期数|缴费类型|投保单号|销售方式|授权年度|备用\r\n
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}||\r\n", bankFront.corpNo, postScript,oppAct, payAmt, oppName, certType, certNum,"0","","0",sourceNoteCode,"0");
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批量代收付请求文件内容:\r\n" + sbFileContent.toString());

            // 上传文件保存本地: YBTRQS+保险公司编码+00099+日期
            String tmpPaySendDate = Format.Date8Format.format(getDayCutTime(p_reqBat.getPayDateTime()));
            
            
            
            String tmpUploadFileName = "YBTRQS" + bankFront.corpNo + "00099" + tmpPaySendDate;
            String tmpLocalMarkPath = getTempFileDirectory(getDayCutTime(p_reqBat.getPayDateTime())) + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批量代收付请求文件保存本机路径: " + tmpLocalMarkPath);

            boolean isSummaryUpload = getBankConfig().getValueAsBool("isSummaryUpload");
            if (isSummaryUpload) {
                FileHelper.appendFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
                retAts.respCode = "0";
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            } else {
                if (FileHelper.existFile(tmpLocalMarkPath)) {
                    retAts.respCode = "0";
                    retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                    retAts.reqSeqID = p_reqBat.reqBatchNO;
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = FailCode.E9981;
                    retAts.writeRetToATS();
                    return retAts;
                }

                // 汇总信息：批次号|业务甲方(保险公司代码)|业务乙方(银行)|申请日期|业务性质|总金额|总笔数\r\n
                String reqBatchNo = bankFront.corpNo + tmpPaySendDate + "01";
                String corpNo = bankFront.corpNo + "000";
                String cdFlag = "S";
                if ("1988".equalsIgnoreCase(p_reqBat.reqHeader.transType)) {
                    cdFlag = "F";
                }
                String totalAmt = StringHelper.amountMultiply100(p_reqBat.totalAmt);
                String totalContent = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}\r\n", reqBatchNo,corpNo,"99",tmpPaySendDate,cdFlag, totalAmt, p_reqBat.totalNum);
                FileHelper.appendFile(tmpLocalMarkPath, totalContent+sbFileContent.toString(), getCharset());

                // 上送银保通服务器
                FtpSet ftpSet = bankFront.getFtpSet("bat");
                FtpReceiver ftpReceiver = null;
                String requestType = getBankConfig().getValueAsString("requestType");
                if (requestType != null && "SFTP".equals(requestType)) {
                    SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                    String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
                    ftpReceiver = sftpPortClient.uploadFile("", tmpLocalMarkPath, sftpFilePath);
                    sftpPortClient.disconnect();
                } else {
                    FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                    ftpReceiver = ftpPortClient.uploadFile(tmpLocalMarkPath, tmpUploadFileName);
                    ftpPortClient.disconnect();
                }

                retAts.respCode = "0";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                if (!ftpReceiver.isCompleted) {
                    retAts.respCode = "-1";
                    retAts.respInfo = ftpReceiver.connMsg;
                } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                    retAts.respInfo = "上传失败";
                    retAts.transState = "BatchFailed";
                    retAts.payInfoCode = "E9999";
                } else {
                    retAts.respInfo = "上传成功";
                    retAts.transState = "Uploaded";
                    retAts.payInfoCode = "I4001";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代收付状态查询
     *
     * @param p_reqQryBat
     * @return
     * @throws Exception
     */
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        try {
            // 下载文件名命名规则:YBTRPS0600009920200309
            String tmpPaySendDate = Format.Date8Format.format(getDayCutTime(p_reqQryBat.getBgnDateTime()));

            String tmpDownFileName = "YBTRPS" + bankFront.corpNo + "00099" + tmpPaySendDate;
            String tmpLocalMarkPath = createTempFileDirectory(tmpPaySendDate) + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);

            FtpSet ftpSet = bankFront.getFtpSet("bat");
            FtpReceiver ftpReceiver = null;
            String requestType = getBankConfig().getValueAsString("requestType");
            if (requestType != null && "SFTP".equals(requestType)) {
                String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + tmpDownFileName;
                WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, tmpLocalMarkPath);
                sftpPortClient.disconnect();
            } else {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName, tmpLocalMarkPath);
                ftpPortClient.disconnect();
            }

            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while(true) {
                        String eachline = tmpReader.readLine();
                        if(StringHelper.isNullOrEmpty(eachline)){
                            break;
                        }
                        if (eachline.indexOf("|") > 0) {
                            String[] bodyValues = eachline.split("\\|");
                            if (bodyValues != null && bodyValues.length > 0) {
                                String tmpBatchNo = bodyValues[1].split("_")[0];
                                if (p_reqQryBat.reqBatchNO.equalsIgnoreCase(tmpBatchNo)) {
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                                    if(p_reqQryBat.reqHeader.transType.equals("1998")){
                                        tmpRetDetail.recAct = bodyValues[2];
                                        tmpRetDetail.recName = bodyValues[5];
                                    } else if(p_reqQryBat.reqHeader.transType.equals("9198")){
                                        tmpRetDetail.payAct = bodyValues[2];
                                        tmpRetDetail.payName = bodyValues[5];
                                    }
                                    tmpRetDetail.postScript = bodyValues[1].split("_")[1];
                                    tmpRetDetail.payAmount = StringHelper.amountDivide100(bodyValues[3]);
                                    tmpRetDetail.result = bodyValues[4];
                                    tmpRetDetail.payInfoCode = bodyValues[4];
                                    if (bodyValues.length > 11) {
                                        tmpRetDetail.memo = bodyValues[11];
                                    }

                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行返回明细数据格式非法!";
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次结果文件内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "批次结果文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeAfterDetail();
        return retAts;
    }
}